import json

from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.views.decorators.csrf import csrf_exempt
from download import gogogo
from files import uploadFiles
from files import uploadArticles
from articles import getArticles
from images import getFirstImageFigureID
from images import getImage
from images import isImageListEmpty
from images import assignImage
from images import getAssignedImageCount
from images import getRemainImageCount, isUserReviewer

from annotate import getTagsByKeyword,getTagsByGO,setTagSelected,tagAImageType,removeATag,saveAsCSV,saveAsXML,saveBoth,saveAll,finalize
from recommend import do_my_work_recommender

def indexView(request):
    return importView(request)

def isAllowToAccess(request):
    try:
        isLoggedIn = request.session['isLoggedIn']
        return isLoggedIn
    except KeyError:
        return False

def importView(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')

    template = loader.get_template('home/import.html')
    username = request.session['username']
    context = RequestContext(request, {
        'isImageListEmpty' : isImageListEmpty(username)
    })
    return HttpResponse(template.render(context))

@csrf_exempt
def uploadAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    result = dict()
    if request.FILES and request.FILES.get('file_upload'):
        result = uploadFiles(request.FILES.getlist('file_upload'))
    return HttpResponse(json.dumps(result), content_type="application/json")

def imagesView(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    template = loader.get_template('home/images.html')
    context = RequestContext(request, {
    })
    return HttpResponse(template.render(context))

def dashboardView(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    elif isImageListEmpty(request.session['username']):
        return HttpResponseRedirect('/home/import')
    
    template = loader.get_template('home/dashboard.html')
    username = request.session['username']
    context = RequestContext(request, {
        'figureID': getFirstImageFigureID(username),
        'totalImages' : getAssignedImageCount(username),
        'remainImages' : getRemainImageCount(username),
        'isReviewer': isUserReviewer(username)
    })

    return HttpResponse(template.render(context))

@csrf_exempt
def getImageAction(request):
    figureID = int(request.GET.get('figureID'))
    offset = int(request.GET.get('offset'))
    username = request.session['username']
    return getImage(username, figureID, offset)

@csrf_exempt
def uploadRelevantArticleAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    result = dict()
    if request.FILES and request.FILES.get('file_upload'):
        result = uploadArticles(request.FILES.get('file_upload'))
    return HttpResponse(json.dumps(result), content_type="application/json")

@csrf_exempt
def getRelevantArticleAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')

    figureID = request.GET.get('figureID')
    result = getArticles(figureID)
    return HttpResponse(json.dumps(result), content_type="application/json")

@csrf_exempt
def getTagsByFigureLegendAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    figureID = int(request.GET.get('figureID'))
    figureLegend = request.GET.get('figureLegend')
    ontologies = request.GET.get('ontologies')
    username = request.session['username']
    print ontologies

    result = do_my_work_recommender(figureID,figureLegend,ontologies, username)
    return HttpResponse(json.dumps(result), content_type="application/json")

@csrf_exempt
def getTagsByKeywordAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    keyword  = request.GET.get('keyword')
    figureID = int(request.GET.get('figureID'))
    ontologies = request.GET.get('ontologies')
    maxLevel = request.GET.get('max-level')
    username = request.session['username']

    result   = getTagsByKeyword(keyword,figureID,ontologies,maxLevel, username)
    return HttpResponse(json.dumps(result), content_type="application/json")

@csrf_exempt
def getTagsByGOAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    keyword  = request.GET.get('keyword')
    figureID = int(request.GET.get('figureID'))
    ontologies = request.GET.get('ontologies')
    username = request.session['username']

    result   = getTagsByGO(keyword,figureID,ontologies, username)
    return HttpResponse(json.dumps(result), content_type="application/json")

@csrf_exempt
def setImageTypeAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    figureID      = int(request.GET.get('figureID'))
    imageTypeName = request.GET.get('imageTypeName')
    username   = request.session['username']
    
    result = tagAImageType(figureID,imageTypeName,username)
    return HttpResponse(json.dumps(result), content_type="application/json")

@csrf_exempt
def setTagSelectedAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    figureID   = int(request.GET.get('figureID'))
    tagID      = int(request.GET.get('tagID'))  
    isSelected = request.GET.get('isSelected') == "true"
    username   = request.session['username']
    
    result     = setTagSelected(figureID,tagID,isSelected,username)
    return HttpResponse(json.dumps(result), content_type="application/json")

@csrf_exempt
def removeTagAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')    
    figureID   = int(request.GET.get('figureID'))
    tagID      = int(request.GET.get('tagID'))
    username   = request.session['username']

    result = removeATag(figureID, tagID, username)
    return HttpResponse(json.dumps(result), content_type="application/json")

@csrf_exempt
def exportAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    
    figureID = int(request.GET.get('figureID'))
    username = request.session['username']
    fileType = request.GET.get('fileType')
    fileName = ''
    isSuccessful = False
    
    if fileType == 'csv':
        isSuccessful,fileName = saveAsCSV(figureID, username)
    elif fileType =='xml':
        isSuccessful,fileName = saveAsXML(figureID, username)
    else:
        isSuccessful,fileName = saveBoth(figureID, username)
        
    result = {
        'isSuccessful': isSuccessful,
        'fileName': fileName,
    }
    return HttpResponse(json.dumps(result), content_type="application/json")

@csrf_exempt
def exportAllAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    
    username = request.session['username']
    isSuccessful,fileName = saveAll(username)
    result = {
        'isSuccessful': isSuccessful,
        'fileName': fileName,
    }
    return HttpResponse(json.dumps(result), content_type="application/json")


@csrf_exempt
def downloadAction(request):
    gogogo()

@csrf_exempt
def finalizeAction(request):
    if not isAllowToAccess(request):
        return HttpResponseRedirect('/accounts')
    
    figureID   = int(request.GET.get('figureID'))
    result = {
        'isSuccessful': finalize(figureID)
    }
    return HttpResponse(json.dumps(result), content_type="application/json")


